package com.zaoqi.service.impl;

import com.zaoqi.pojo.PageBean;
import com.zaoqi.pojo.User;
import com.zaoqi.repository.UserRepository;
import com.zaoqi.service.UserService;
import com.zaoqi.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Optional<User> findById(int id) {
        return userRepository.findById(id);
    }

    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public PageBean getUsers(int pageNum, int pageSize, String username) {
        // 分页查询，按用户名筛选
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        Page<User> page;
        if (username != null && !username.isEmpty()) {
            page = userRepository.findByUsernameContaining(username, pageRequest);
        } else {
            page = userRepository.findAll(pageRequest);
        }

        // 封装分页结果
        PageBean pageBean = new PageBean();
        pageBean.setPageNum(page.getNumber() + 1);
        pageBean.setPageSize(page.getSize());
        pageBean.setTotal(page.getTotalElements());
        pageBean.setUsers(page.getContent());
        return pageBean;
    }

    @Override
    public void createUser(User user) {
        if (userRepository.findByUsername(user.getUsername()).isPresent()) {
            throw new RuntimeException("用户名已存在");
        }
        userRepository.save(user);
    }

    @Override
    public boolean deleteUserByUsername(String username) {
        Optional<User> userOptional = userRepository.findByUsername(username);
        if (userOptional.isPresent()) {
            userRepository.delete(userOptional.get());
            return true;
        }
        return false;
    }

    @Override
    public boolean isAdmin(String token) {
        // 从 token 中解析角色信息
        String role = (String) JwtUtils.parseJWT(token).get("role");
        return "ADMIN".equals(role);
    }
}
